package com.yand.serviceimpl.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yand.api.entity.common.Result;
import com.yand.api.entity.system.TSysUser;
import com.yand.api.service.system.UserService;
import com.yand.mapper.system.TSysUserMapper;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/**
 * 用户接口实现类
 */
@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private TSysUserMapper userMapper;

    @Override
    public PageInfo<TSysUser> queryUserList(TSysUser user) {

        PageHelper.startPage(user.getPageNum(), user.getPageSize());

        return PageInfo.of(userMapper.selectUsers(user));
    }

    @Override
    public TSysUser getUserById(int userId) {
        TSysUser user = new TSysUser();
        if(userId == 0){
            return user;
        }
        user.setUserId(userId);
        return userMapper.selectUsers(user).get(0);
    }

    @Override
    public void insertUser(TSysUser user) {
        user.setRPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //获取当前时间的格式化字符串
        String now  = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());
        user.setExtension2(now);
        userMapper.insert(user);
    }

    @Override
    public void updateUser(TSysUser user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void deleteUser(int userId) {
        userMapper.deleteByPrimaryKey(userId);
    }


    /**
     * 更改密码
     * 1, 校验当前密码是否正确
     * 2, 更新新密码
     */
    @Override
    public Result updatePwd(String oldPassword, String newPassword) {
        //获取当前登录人
        TSysUser user = (TSysUser)SecurityUtils.getSubject().getPrincipal();
        //校验旧密码是否正确
        if(!DigestUtils.md5DigestAsHex(oldPassword.getBytes()).equals(user.getRPassword())){
          return new Result(1,"旧密码错误");
        }
        //设置密码
        user.setRPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));

        //更新用户
        updateUser(user);

        return new Result(0);

    }
}
